/**
 * 
 */

package com.chengyu.eyc.config.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import com.chengyu.eyc.enums.UserTypeEnums;
import com.chengyu.eyc.model.EycUser;
import com.chengyu.eyc.service.EycService;
import com.chengyu.eyc.utils.RSAUtils;

import cn.hutool.core.util.StrUtil;

/**
 * @author kevin
 *
 */
@Component
public class EycUserDetailsAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    @Autowired
    private EycService eycService;

    /**
     * @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider#additionalAuthenticationChecks(org.springframework.security.core.userdetails.UserDetails,
     *      org.springframework.security.authentication.UsernamePasswordAuthenticationToken)
     */
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) {
        // 实现父类方法
    }
    
    private String getPassword(String password) {
       password=  new String(RSAUtils.decryptData(
           Base64Utils.decode(password.getBytes())));
      return password;
    }
    /**
     * @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider#retrieveUser(java.lang.String,
     *      org.springframework.security.authentication.UsernamePasswordAuthenticationToken)
     */
    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) {
        EycUser eycUser = eycService.searchEycUserByUserIdAndUserType(username,UserTypeEnums.INNER_USER.getCode());
        if (eycUser == null) {
            throw new BadCredentialsException("账号不存在");
        }
        if (!StrUtil.equals((String)authentication.getCredentials(),getPassword(eycUser.getPassword()))) {
            throw new BadCredentialsException("密码不正确");
        }

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        return new User(username, (String)authentication.getCredentials(), grantedAuthorities);
    }

}
